package com.xing.lei.happy.dao;

import com.xing.lei.happy.utils.DataSourceUtil;
import com.xing.lei.happy.utils.DatabaseUtils;
import com.xing.lei.happy.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BaseService {

    protected static DataSource dataSource;
    @Bean
    public static DataSource getDataSource() {
        if (dataSource == null) {
            String sourceUrl = "jdbc:oracle:thin:@172.16.7.146:1521:orcl";
            String sourceUsername = "RHM_WXP";
            String sourcePassword = "RHM_WXP";
            try {
                dataSource = DataSourceUtil.createOracleDataSource(sourceUrl, sourceUsername, sourcePassword);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return dataSource;
    }
    public  static Table getTable() {
        if (dataSource == null) {
            dataSource = getDataSource();
        }
        return new Table( getDataSource());
    }

    public static List<Map<String, Object>> getTableData(DataSource dataSource, String tableName,String sqlStr) throws SQLException {
        List<Map<String, Object>> dataList = new ArrayList<>();
        String sql = "SELECT * FROM " + tableName;
        if(StringUtils.isNotBlank(sqlStr)){
            sql += " WHERE " + sqlStr;
        }

        try (Connection connection = dataSource.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql);
             ResultSet resultSet = statement.executeQuery()) {

            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();

            while (resultSet.next()) {
                Map<String, Object> row = new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Object value = resultSet.getObject(i);
                    row.put(columnName, value);
                }
                dataList.add(row);
            }
        }

        return dataList;
    }

}
